import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:ecy_app_flutter/constant/constant.dart';
import 'package:ecy_app_flutter/ecycommon/EcyCommonWidgets.dart';
import 'package:ecy_app_flutter/routes/goods/model/EcyGoodsHomeIPListModel.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../../constant/color_constant.dart';
import 'package:flutter_draggable_gridview/flutter_draggable_gridview.dart';

import '../../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../../ecycommon/utils/EcyRandomUtil.dart';
import '../../../../model/EcyApiCommonResponse.dart';
import '../../model/EcyGoodsHomeIPModel.dart';

class EcyGoodsIPSelectPage extends EcyCommonBaseWidget {
  // final T listModel;
  // final ValueChanged<List<dynamic>> onSelected;
  // EcyGoodsIPAndCategorySelectPage(this.listModel, this.onSelected);
  @override
  _EcyGoodsIPSelectPageState createState() {
    return _EcyGoodsIPSelectPageState(this);
  }
}

class _EcyGoodsIPSelectPageState extends EcyCommonBaseWidgetState {
  int currentIndex = 0;
  bool requesting = false;
  late EcyGoodsHomeIPListModel listModel =
      EcyGoodsHomeIPListModel(0, 0, 0, [], false, 0);
  final EcyCommonBaseWidget controller;

  _EcyGoodsIPSelectPageState(this.controller);

  void requestData() async {
    super.requestData();
    controller.showLoading();
    var response = await Future.wait([
      EcyRequestbasemanager().post(
          "/app/api/app/commodityIp/list", {"size": "100", "current": "1", "name": ""}),
    ]);
    print("response" + response.toString());
    controller.dismissLoading();
    if (response != null) {
      var _ipResp = response[0];
      if (_ipResp != null) {
        reloadIPArea(_ipResp);
      }
    }
  }

  void reloadIPArea(_ipResp) {
    var _ipRespModel =
        EcyApiCommonResponse.fromJson(_ipResp, (_ipResp) => json);
    if (_ipRespModel.code == 0) {
      EcyGoodsHomeIPListModel _ipListModel =
          EcyGoodsHomeIPListModel.fromJson(_ipResp["data"]);
      setState(() {
        listModel = _ipListModel;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    requestData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: ColorConstant.White,
        // appBar: AppBar(
        //   backgroundColor: ColorConstant.White,
        //   title: Text(
        //     "全部",
        //     style: TextStyle(
        //         fontSize: 16.sp,
        //         color: Color(0xD9000000),
        //         fontWeight: FontWeight.w700),
        //   ),
        // ),
        body: NestedScrollView(
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return <Widget>[
              SliverAppBar(
                backgroundColor: ColorConstant.White,
                title: Text('Header'),
                floating: true,
                pinned: true,
                snap: false,
                expandedHeight: 200,
                flexibleSpace: FlexibleSpaceBar(
                  title: Text('Flexible Header'),
                  background: Image.network(
                    'https://via.placeholder.com/800x200',
                    fit: BoxFit.cover,
                  ),
                ),
              ),
            ];
          },
          body: CustomScrollView(
            slivers: <Widget>[
              SliverGrid(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  crossAxisSpacing: 10.0,
                  mainAxisSpacing: 10.0,
                ),
                delegate: SliverChildBuilderDelegate(
                  (BuildContext context, int index) {
                    return Container(
                      color: Colors.blue[100 * (index % 9)],
                      child: Center(
                        child: Text(
                          'Grid Item $index',
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                    );
                  },
                  childCount: 20,
                ),
              ),
              SliverToBoxAdapter(
                child: SizedBox(height: 20), // 间距
              ),
              SliverGrid(
                gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                  maxCrossAxisExtent: 150.0,
                  crossAxisSpacing: 10.0,
                  mainAxisSpacing: 10.0,
                ),
                delegate: SliverChildBuilderDelegate(
                  (BuildContext context, int index) {
                    return Container(
                      decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Center(
                        child: Text(
                          'Grid Item ${index + 20}', // 从20开始，避免与前一个GridView的索引冲突
                          style: TextStyle(fontSize: 16),
                        ),
                      ),
                    );
                  },
                  childCount: 15,
                ),
              ),
            ],
          ),
        ));
  }

  List<DraggableGridItem> _listOfDraggableGridItem(
      EcyGoodsHomeIPListModel list) {
    List<DraggableGridItem> itemArr =
        List<DraggableGridItem>.empty(growable: true);
    list.records.forEach((item) {
      itemArr.add(DraggableGridItem(
          isDraggable: true,
          child: Flexible(
//               decoration: BoxDecoration(
// // borderRadius: BorderRadius.all(Radius.circular(8.r)),
//                 color: ColorConstant.CommonColor, //设置背景色为黑色
//               ),
              child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              (item.id == "-1"
                  ? Container(
                      width: 44.w,
                      height: 44.w,
                      child: Image.asset(item.iconUrl ?? ""),
                    )
                  : CachedNetworkImage(
                      width: 44.w,
                      height: 44.w,
                      imageUrl: item.iconUrl ?? EcyRandomUtil.randomIconUrl(),
                      imageBuilder: (context, imageProvider) => Container(
                        decoration: BoxDecoration(
                            borderRadius:
                                BorderRadius.all(Radius.circular(8.r)),
                            image: DecorationImage(
                                image: imageProvider, fit: BoxFit.contain)),
                      ),
                      // placeholder: (context, url) =>
                      //     CircularProgressIndicator(),
                      errorWidget: (context, url, error) => Icon(Icons.error),
                    )),
              SizedBox(height: 8.h),
              Text(
                item.name ?? item.remark ?? "",
                style: TextStyle(
                    fontWeight: FontWeight.w300,
                    fontSize: 12.sp,
                    color: Color(0xD9000000)),
              )
            ],
          ))));
    });
    if (itemArr.isEmpty) {
      itemArr.add(DraggableGridItem(child: Text("")));
    }
    return itemArr;
  }

  @override
  void dispose() {
    // 清理控制器，避免内存泄漏
    super.dispose();
  }
}
